<template>
    <div class="login-container">
      <el-row type="flex" justify="center" align="middle" class="login-row">
        <el-col :span="8">
          <el-card class="login-card">
            <h2 class="login-title">用户注册</h2>
            <el-form @submit.native.prevent="register" class="login-form">
              <el-form-item label="名称：" required>
                <el-input v-model="username" placeholder="请输入名称"></el-input>
              </el-form-item>
              <el-form-item label="密码：" required>
                <el-input type="password" v-model="password" placeholder="请输入密码"></el-input>
              </el-form-item>
              <el-form-item label="邮箱：" required>
                <el-input v-model="email" placeholder="请输入邮箱"></el-input>
              </el-form-item>
              <el-form-item label="验证码：" required>
                <div class="verification-container">
                  <el-input v-model="emailCode" placeholder="请输入邮箱验证码" class="email-code-input"></el-input>
                  <el-button
                    :disabled="isDisabledSendButton"
                    @click="sendEmailCode"
                    class="send-code-button"
                  >
                    {{ buttonText }}
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" native-type="submit" class="login-button">注册</el-button>
              </el-form-item>
            </el-form>
            <a href="login.html" class="register-link">登录</a>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, watch } from 'vue';
  import axios from 'axios';
  import { ElMessage } from 'element-plus';
  
  // 定义响应式数据
  const username = ref('');
  const password = ref('');
  const email = ref('');
  const emailCode = ref('');
  const countdown = ref(60); // 倒计时初始值为 60 秒
  const isDisabledSendButton = ref(false); // 控制“发送验证码”按钮的禁用状态
  const buttonText = ref('发送验证码'); // 按钮文本
  
  const emailCodeSuccess = ref(false); // 邮箱验证码是否校验成功
  
  // 发送邮箱验证码
  const sendEmailCode = () => {
    if (!email.value) {
      ElMessage.error('请先输入邮箱地址');
      return;
    }
  
    axios.get('/api/email/general_email_sender?email=' + email.value)
      .then(res => {
        
        
        if (res.data.code === 200) {
          ElMessage.success('验证码已发送到您的邮箱，请查收');
          isDisabledSendButton.value = true; // 发送成功后禁用按钮
          startCountdown(); // 开始倒计时
        } else {
          ElMessage.error('发送失败：' + res.data.msg);
        }
      })
      .catch(err => {
        console.log(err);
        ElMessage.error('发送失败，请检查网络或稍后重试');
      });
  };
  
  // 倒计时逻辑函数
  const startCountdown = () => {
    countdown.value = 60; // 重置倒计时
    buttonText.value = `剩余 ${countdown.value} 秒`;
    const intervalId = setInterval(() => {
      countdown.value--;
      buttonText.value = `剩余 ${countdown.value} 秒`;
  
      if (countdown.value <= 0) {
        clearInterval(intervalId);
        isDisabledSendButton.value = false; // 恢复按钮状态
        buttonText.value = '发送验证码';
      }
    }, 1000);
  };
  
  // 监听邮箱验证码长度，自动校验
  watch(emailCode, (newEmailCode) => {
    if (newEmailCode.length === 6) {
      axios.post('/api/email/email_verify', {
        email: email.value,
        code: newEmailCode
      }).then(res => {
        if (res.data.code === 200) {
          emailCodeSuccess.value = true;
          ElMessage.success('验证码校验成功，请继续填写注册信息');
        } else {
          emailCodeSuccess.value = false;
          ElMessage.error('验证码不正确，请重新输入');
        }
      }).catch(err => {
        console.log(err);
        emailCodeSuccess.value = false;
        ElMessage.error('验证码验证失败，请稍后重试');
      });
    } else {
      emailCodeSuccess.value = false;
    }
  });
  
  // 注册函数
  const register = () => {
    if (!emailCodeSuccess.value) {
      ElMessage.error('请先完成邮箱验证码校验');
      return;
    }
  
    axios({
      method: 'post',
      url: "/api/users/register",
      data: {
        username: username.value,
        password: password.value,
        email: email.value,
        emailCode: emailCode.value
      }
    }).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('注册成功，即将跳转到登录页面');
        setTimeout(() => {
          window.location.href = '/login';
        }, 1000);
      } else {
        ElMessage.error('注册失败：' + res.data.msg);
      }
    }).catch(err => {
      console.log(err);
      ElMessage.error('注册失败，请稍后重试');
    });
  };
  </script>
  
  <style scoped>
  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #ffffff;
  }
  
  .login-row {
    height: 100%;
  }
  
  .login-card {
    width: 300px;
    padding: 20px;
    background-color: #ffffff;
    border-radius: 5px;
  }
  
  .login-title {
    text-align: center;
    margin-bottom: 20px;
    color: #000000;
  }
  
  .login-form {
    color: #000;
  }
  
  .verification-container {
    display: flex;
    align-items: center;
  }
  
  .email-code-input {
    width: 120px;
    margin-right: 10px;
  }
  
  .send-code-button {
    margin-right: 10px;
  }
  
  .login-button {
    width: 100%;
    padding: 10px;
    background-color: #409EFF;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
  }
  
  .register-link {
    display: block;
    text-align: center;
    margin-top: 20px;
    color: #409EFF;
  }
  
  .success-msg {
    color: green;
  }
  
  .error-msg {
    color: red;
  }
  </style>
  